import os

from flask_cors import cross_origin
from flask_socketio import SocketIO, emit

from flask import Flask, render_template, request, redirect, url_for, flash, session
from flask_sqlalchemy import SQLAlchemy
from openai import OpenAI

from models import db, User, Applicant, Company
from config import *
import traceback

from routes import register_blueprints
from utils.socketio_service import initialize_socketio

app = Flask(__name__)
app.secret_key = 'your_secret_key'

# 允许的文件扩展名
ALLOWED_EXTENSIONS = {'docx', 'pdf'}

# 加载配置
app.config.from_object(Configjx)
app.config.from_object(Configly)
app.config.from_object(Confighyb)

# 初始化 SQLAlchemy
db.init_app(app)  # 确保db实例绑定到app

with app.app_context():
    db.create_all()  # 创建所有表

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS



@app.route('/')
def hello_world():
    return render_template('common/index.html')

@app.route('/loginView')
def login():
    return render_template('common/login.html')

@app.route('/registerView')
def register():
    return render_template('common/register.html')

@app.route('/applicant/dashboard')
def applicant_dashboard():
    if 'user_id' in session and session['role'] == 'applicant':
        print(session)
        return render_template('applicant/dashboard.html', full_name=session.get('full_name', ''))
    return redirect(url_for('login'))

@app.route('/company/dashboard')
def company_dashboard():  # 修改为 employer_dashboard
    if 'user_id' in session and session['role'] == 'company':
        print(session)
        return render_template('company/dashboard.html', company_name=session.get('company_name', ''))
    return redirect(url_for('login'))


@app.route('/applicant/sim_interview')
def candidate_interview_room():
    return render_template('applicant/interviewindex.html')

@app.route('/applicant/interview')
def candidate_interview():
    return render_template('applicant/interviewCenter.html')

@app.route('/applicant/personal_center')
def candidate_profile():
    return render_template('applicant/profile.html')

@app.route('/applicant/resume')
def candidate_resume():
    return render_template('applicant/resume_uoload.html')

@app.route('/applicant/reports')
def applicant_report():
    return render_template('applicant/reports.html')

@app.route('/company/jobManage')
def company_jobManage():
    return render_template('company/jobManage.html')

@app.route('/applicant/analyze_resume')
def company_analyze_resume():
    return render_template('applicant/analyze_resume.html')

@app.route('/applicant/resume_report')
def company_resume_report():
    return render_template('applicant/resume_report.html')

@app.route('/applicant/upload_resume')
def company_upload_resume():
    return render_template('applicant/resume_submint.html')

@app.route('/applicant/interview_manage')
def company_interview_manage():
    return render_template('applicant/interview_manage.html')

@app.route('/company/manage_applicant')
def company_manage_applicant():
    return render_template('company/manage_applicant.html')

@cross_origin(origins=["https://cdn.novadata.top","http://localhost:5000"])
@app.route('/applicant/avatar')
def applicant_avatar():
    return render_template('applicant/avatar.html')

@app.route('/company/manage_interview')
def company_manage_interview():
    return render_template('company/manage_interview.html')

@app.route('/applicant/interviewindex')
def candidate_interview_index():
    return render_template('applicant/interviewindex.html')

@app.route('/applicant/resume_manage')
def applicant_resume_manage():
    return render_template('applicant/resume_manage.html')

@app.route('/applicant/TestConfig')
def applicant_TestConfig():
    return render_template('applicant/TestConfig.html')

@app.route('/company/companyCenter')
def company_companyCenter():
    return render_template('company/profile.html')

@app.route('/logout')
def logout():
    # 删除会话中的所有数据
    session.clear()
    # 重定向到首页
    return redirect(url_for('hello_world'))

@app.route('/company/score-weights')
def company_score_weights():
    if 'user_id' in session and session['role'] == 'company':
        return render_template('company/score_weights.html')
    return redirect(url_for('login'))


# 初始化 OpenAI 客户端
client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)

def stream_chat(messages):
    answer_content = ""

    stream = client.chat.completions.create(
        model="deepseek-v3",
        messages=messages,
        stream=True
    )

    for chunk in stream:
        if not getattr(chunk, 'choices', None):
            continue

        delta = chunk.choices[0].delta

        if not hasattr(delta, 'content'):
            continue

        if not getattr(delta, 'content', None):
            continue

        answer_content += delta.content

    return answer_content

def queryTomessage(query):
    message = query
    return message

# @app.route('/avatar/chat',methods=['POST'])
# def avatar_chat():
#     data = request.json
#     query = data['query']
#     print(query)
#     # result={}
#     # result['audio_offsets'] = ""
#     # audio_relative_path = reply.content[len(TmpDir.tmp_root_path()):]
#     # result['audio'] = f'/audios{"" if audio_relative_path[0] == "/" else "/"}{audio_relative_path}'
#     # result['blendshapes'] = voice_engine.blend_shapes
#
#     result={
#         "audio": '/static/audio/ss.mp3',
#         "blendshapes":'',
#         "audio_offsets":'',
#         'text':'12'
#     }
#     return result







register_blueprints(app)
socketio = initialize_socketio(app)

if __name__ == '__main__':
    socketio.run(app, debug=True,allow_unsafe_werkzeug=True)